package com.xiaoxi.xioj.judge.codesandbox.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.xiaoxi.xioj.common.ErrorCode;
import com.xiaoxi.xioj.exception.BusinessException;
import com.xiaoxi.xioj.judge.codesandbox.CodeSandbox;
import com.xiaoxi.xioj.judge.codesandbox.model.ExecuteCodeRequest;
import com.xiaoxi.xioj.judge.codesandbox.model.ExecuteCodeResponse;
import org.apache.commons.lang3.StringUtils;

/**
 *  远程代码沙箱
 */
public class RemoteCodeSandbox implements CodeSandbox {
    // 定义安全认证请求头
    public static final String AUTH_REQUEST_HEADER = "auth";
    public static final String AUTH_REQUEST_SECRTY = "secretKey";

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        String url = "http://localhost:8090/executeCode";
        String json = JSONUtil.toJsonStr(executeCodeRequest);

        String responseStr = HttpUtil.createPost(url)
                .header(AUTH_REQUEST_HEADER, AUTH_REQUEST_SECRTY)
                .body(json)
                .execute()
                .body();
        if (StringUtils.isBlank(responseStr)){
            throw new BusinessException(ErrorCode.API_REQUEST_ERROR, "executeCode remoteSandbox error, message =" + responseStr);
        }
        return JSONUtil.toBean(responseStr, ExecuteCodeResponse.class);
    }
}
